from apscheduler.schedulers.background import BackgroundScheduler

from lib.init.scheduler_init import SchedulerInit


class SchedulerHandler(object):
    def __init__(self):
        # 创建后台执行的 schedulers
        self.scheduler = BackgroundScheduler()

    def handler(self, func, server_id):
        # 添加调度任务
        # 调度方法为 timedTask，触发器选择 interval(间隔性)，间隔时长为 1 秒
        s_obj = SchedulerInit.server_schedule.get(server_id)
        prop = s_obj.args
        if s_obj.trigger == 'interval':
            self.scheduler.add_job(func, 'interval', **prop, id=server_id)
        elif s_obj.trigger == 'cron':
            self.scheduler.add_job(func, 'cron', **prop, id=server_id)

    def start(self):
        self.scheduler.start()
